package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketRegion;
import com.cskaoyan.market.db.domain.SelfMarketRegion;
import com.cskaoyan.market.service.MarketRegionService;
import com.cskaoyan.market.service.impl.MarketRegionServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/admin/region/*")
public class RegionController extends HttpServlet {
    MarketRegionService marketRegionService = new MarketRegionServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String op = req.getRequestURI().replace(req.getContextPath() + "/admin/region/", "");
        System.out.println("dispatcher: GET " + op);
        if ("list".equals(op)){
            list(req,resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        List<MarketRegion> regionList = marketRegionService.getRegionList(0);
        List<SelfMarketRegion> selfMarketRegions = marketRegionService.packageMarketRegionList(regionList);
        Object ok = ResponseUtil.okList(selfMarketRegions);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        String s = objectMapper.writeValueAsString(ok);
        resp.getWriter().println(s);
    }

}
